// Simple streaming test against the AI API using the required 3-field JSON content
// Usage: node scripts/ai_stream_test.js

const https = require('https');

const API_URL = 'https://wpe8xarnv3xz6z1d.ai-plugin.io/chat/completions';
const API_KEY = 'app-DerklWxkjYSKzHmWmuILybha'; // Provided key

// Build messages[0].content as a JSON string containing the three fields
const payload = {
  model: 'gpt-3.5-turbo',
  messages: [
    {
      role: 'user',
      content:
        '{"resource_type": "科研专家","customer_needs": "【需求详情】我司想研发上线一个心理健康类的微信小程序，用于初中学校里心理老师对本校学生日常心理的监控与疏导。","references": "李老师，博士，副研究员，硕士生导师。一直在华东师范大学上海数字化教育装备工程技术研究中心和教育信息技术系工作，从事教育信息化方面的研究和服务工作。近年来主要关注人工智能教育应用、学习分析、中小学人工智能和编程教育、智慧校园建设等。"}',
    },
  ],
  stream: true,
};

const requestBody = JSON.stringify(payload);

const req = https.request(
  API_URL,
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json; charset=UTF-8',
      'Accept': 'text/event-stream, application/json',
      'Authorization': `Bearer ${API_KEY}`,
      'Cache-Control': 'no-cache',
      Connection: 'keep-alive',
    },
  },
  (res) => {
    console.log('Status:', res.statusCode);
    console.log('Headers:', res.headers);

    let buffer = '';
    let fullContent = '';

    res.on('data', (chunk) => {
      const text = chunk.toString('utf-8');
      buffer += text;

      // Process by lines for SSE
      const lines = buffer.split(/\r?\n/);
      // Keep the last partial line in buffer
      buffer = lines.pop();

      for (const line of lines) {
        const trimmed = line.trim();
        if (!trimmed) continue;

        if (trimmed.startsWith('data: ')) {
          const data = trimmed.slice(6).trim();
          if (data === '[DONE]') {
            console.log('Stream completed.');
            continue;
          }
          try {
            const json = JSON.parse(data);
            const choices = json.choices;
            if (Array.isArray(choices) && choices.length > 0) {
              const delta = choices[0].delta || {};
              if (typeof delta.content === 'string') {
                fullContent += delta.content;
                process.stdout.write(delta.content);
              }
            }
          } catch (err) {
            console.warn('Failed to parse SSE chunk:', data);
          }
        } else {
          // Non-SSE lines (sometimes servers send extra info)
          // console.log('Non-SSE line:', trimmed);
        }
      }
    });

    res.on('end', () => {
      console.log('\n\n---');
      console.log('Total content length:', fullContent.length);
      console.log('Preview:', fullContent.slice(0, 200));

      // Control: also run a non-stream request once (Authorization only)
      console.log('Running control: non-stream mode (Authorization only)...');
      const nonStreamPayload = { ...payload, stream: false };
      const nonStreamBody = JSON.stringify(nonStreamPayload);

      const req2 = https.request(
        API_URL,
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json; charset=UTF-8',
            'Accept': 'application/json',
            'Authorization': `Bearer ${API_KEY}`,
          },
        },
        (res2) => {
          console.log('Non-stream Status:', res2.statusCode);
          let buf = '';
          res2.on('data', (c) => (buf += c.toString('utf-8')));
          res2.on('end', () => {
            try {
              const json = JSON.parse(buf);
              const choices = json.choices || [];
              const content = choices[0]?.message?.content || '';
              console.log('Non-stream content length:', content.length);
              console.log('Content preview:', content.slice(0, 500));
            } catch (e) {
              console.error('Failed to parse non-stream response:', e.message);
              console.log('Raw body preview:', buf.slice(0, 500));
            }
          });
        }
      );
      req2.on('error', (err) => console.error('Non-stream request error:', err));
      req2.write(nonStreamBody);
      req2.end();
    });
  }
);

req.on('error', (err) => {
  console.error('Request error:', err);
});

req.write(requestBody);
req.end();